package com.example.lucene.test;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.similarities.ClassicSimilarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;

/**
 * @Author yanggld
 * @Date 2019/5/24-17:24
 * @Description
 */
public class Searcher {

	public static void search(String indexDir,String q)throws Exception{

		//得到索引文件存储目录
		Directory dict = FSDirectory.open(FileSystems.getDefault().getPath(indexDir));
		//创建索引读取器
		IndexReader reader = DirectoryReader.open(dict);
		//创建索引搜索器
		IndexSearcher searcher = new IndexSearcher(reader);

		//设置相关性排序为TF/IDF 排序
		ClassicSimilarity tf_idf = new ClassicSimilarity();
		searcher.setSimilarity(tf_idf);

		//创建分析器，要跟前面创建索引用到的分析器相同，否则会出错
		Analyzer analyzer = new SmartChineseAnalyzer();

		//建立查询解析器，第一参数是查询的field, 第二个参数是分析器
//		QueryParser parser = new QueryParser("content", analyzer);
//		//根据传进来的字符串q查找
//		Query query = parser.parse(q);
//		System.out.println("分析器："+query.toString());
		//检索开始时间
		long start = System.currentTimeMillis();
		BooleanQuery.Builder builder = new BooleanQuery.Builder();
		BooleanQuery.Builder categoryBuilder = new BooleanQuery.Builder();
		Term term = new Term("content", q);
		TermQuery termQuery = new TermQuery(term);
		categoryBuilder.add(termQuery,BooleanClause.Occur.SHOULD);
		builder.add(categoryBuilder.build(),BooleanClause.Occur.MUST);
		//查询得到搜索命中的结果集，第一个参数是QueryParser生成的Parser，第二个参数是ScoreDos的最大文件数
		TopDocs hits = searcher.search(builder.build(), 10);

		//检索结束时间
		long end=System.currentTimeMillis();

		System.out.println("检索 " + q + " ，总共花费" + (end - start) + "毫秒" + "查询到" + hits.totalHits + "个记录");

		//遍历hits中的top-n文件集，也就是ScoreDoc
		for(ScoreDoc scoreDoc:hits.scoreDocs){
			//通过文件的序号找到文件所在路径
			Document doc = searcher.doc(scoreDoc.doc);
			System.out.println(" 相关性是：" + String.valueOf(scoreDoc.score));
		}

		//关闭reader
		reader.close();
	}

	//测试
	public static void main(String[] args) throws IOException {
		String indexDir="index";
		// 处理输入
//		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//		String str = null;
//		System.out.println("请输入你要搜索的关键词:");
//		try {
//			str = br.readLine();
//			System.out.println();
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		String str = "天";
		try {
			search(indexDir, str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}